<template>
  <div style="text-align: center;padding-top: 40px;margin-left: -70px">

    <!--    <h1 style="color: #60ce51">登录</h1>-->
    <div style="padding-bottom: 0px;padding-left: 60px">
      <el-avatar :size="80"
                 :src="imgPath?imgPath:'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'"></el-avatar>
    </div>
    <p class="login_title">
      <span :class="value ? 'isActiveTitle' : ''" @click="value = true">账号登录</span>
      <span :class="value ? '' : 'isActiveTitle'" @click="value = false">短信登录</span>
    </p>

    <!--    账号密码登录-->
    <el-form :model="user" status-icon
             :rules="rules" ref="user" label-width="80px"
             class="demo-ruleForm" v-show="value">
      <el-form-item label="" prop="username">
        <el-input type="text" v-model="user.username" autocomplete="off" style="width: 80%" >
          <template slot="prepend">账号</template>
        </el-input>
        <span style="color: red;float:right;">{{errorMsg?errorMsg:''}}</span>
      </el-form-item>
      <el-form-item label="" prop="password">

        <el-input type="password" v-model="user.password" autocomplete="off" style="width: 80%">
          <template slot="prepend">密码</template>
        </el-input>
      </el-form-item>
      <el-checkbox v-model="loginAuto">自动登录</el-checkbox>
      <el-form-item style="margin-top: 10px">
        <el-button type="primary" @click="submitForm('user')">登录</el-button>
        还没有账号？
        <el-button type="text"  @click="toRegister">立即注册</el-button>
      </el-form-item>
    </el-form>

    <!--    手机号登录-->
    <el-form :model="user_phone" status-icon
             :rules="rules1" ref="user_phone" label-width="80px"
             class="demo-ruleForm" v-show="!value">
      <el-form-item label="" prop="phone">
        <el-input type="text" v-model="user_phone.phone" autocomplete="off" style="width: 80%" >
          <template slot="prepend">手机号</template>
        </el-input>
        <span style="color: red;float:right;">{{errorMsg?errorMsg:''}}</span>
      </el-form-item>
      <el-form-item label="" prop="code">

        <el-input type="password" v-model="user_phone.code" autocomplete="off" style="width: 80%">
          <template slot="prepend">验证码</template>
          <el-button slot="append" icon="el-icon-message"
                     :disabled="!show" @click="sendSMS()">
          </el-button>
        </el-input>
      </el-form-item>
      <el-form-item style="margin-top: 53px">
        <el-button type="primary" @click="submitForm('user_phone')">登录</el-button>
        还没有账号？
        <el-button type="text"  @click="toRegister">立即注册</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>


export default {
  name: "Login",
  data(){
    var validateUsername = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入账号'));
      } else {
        // axios数据库查询是否有此用户
        this.axios.get('/login/isExist/'+this.user.username+'').then(res=>{
          if(res.data.code === 0){
            //有该用户，显示图片路径
            this.imgPath = res.data.data.imgPath
            //清空错误信息
            this.errorMsg = ''
            callback()
          }else{
            callback(new Error(res.data.data.errMsg))
            this.imgPath = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
          }
        })


      }
    };
    var validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'));
      }
      //校验手机号
      var myreg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      setTimeout(() => {
        if (!myreg.test(value)) {
          callback(new Error('请输入正确的手机号'));
        }
        else {
          // axios数据库查询是否有此用户
          this.axios.get('/login/isUserPhone/'+this.user_phone.phone+'').then(res=>{
            if(res.data.code === 0){
              //有该用户，显示图片路径
              this.imgPath = res.data.data.imgPath
              //清空错误信息
              this.errorMsg = ''
              callback()
            }else{
              callback(new Error(res.data.data.errMsg))
              this.imgPath = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
            }
          })
        }
      }, 500);
    };
    var validateCode = (rule, value, callback) => {
      let reg = /^\d{6}$/;
      if(!(reg.test(value))) {
        return callback(new Error('请填写6位数字验证码'));
      }else{
        callback();
      }
    }

    return{
      imgPath:'',
      errorMsg:'',
      user: {
        username: '',
        password: '',
      },
      user_phone:{
        phone:'',
        code:'',
      },

      value:true,  //账号密码或者短信登录
      show:true,  //发送短信按钮是否可用
      loginAuto:false, //自动登录
      rules: {
        username: [
          { validator: validateUsername, trigger: 'blur' }
        ],
        password: [
          { validator: validatePassword, trigger: 'blur' }
        ],
      },
      rules1:{
        phone:[
          { validator: validatePhone, trigger: 'blur'}
        ],
        code:[
          { validator: validateCode, trigger: 'blur'}
        ]
      }
    };

  },
  mounted() {
    this.getCookie();
  },
  methods:{
    //账号密码登录
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var url = '';
          var data = '';
          if(this.value){
            //账号密码登录
            url = '/login/toLogin'
            data = this.user
          }else{
            //手机号登录
            url = '/login/toLoginByPhone'
            data = this.user_phone
          }
          console.log(data)
          //向后台发送请求
          this.axios.post(url,data).then(res =>{
            if(res.data.code === 0){
              this.$message.success("登录成功")
              //接收后台的user对象，存入Vuex
              this.$store.dispatch(
                  'userinfo/changeuserinfo',
                  {
                    user:res.data.data.user
                  }
              )
              //用户名存入localStrange
              localStorage.setItem("username",res.data.data.user.username)


              if(this.loginAuto){
                //勾选了自动登录
                //存入cookie
                this.setCookie(this.user.username,this.user.password,1);
              }else{
                this.setCookie("","",0)
              }

              //跳转首页
              this.$router.replace({path:'/index'})
            }else{
              this.$message.error(res.data.data.errMsg)
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },



    //发送验证码
    sendSMS () {

      //校验手机号
      var myreg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if(!myreg.test(this.user_phone.phone)){
        this.$message.error('请填写正确的手机号');
      }else {
        const TIME_COUNT = 60 //更改倒计时时间

        this.show = false //按钮不可用
        if (!this.timer) {
          this.count = TIME_COUNT;
          this.show = false;
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= TIME_COUNT) {
              this.count--;
            } else {
              this.show = true;
              clearInterval(this.timer); // 清除定时器
              this.timer = null;
            }
          }, 1000)
        }

        //发送验证码
        this.axios.post('/register/sendSMS/'+this.user_phone.phone+'').then(res=>{
          if(res.data.code === 0){
            //console.log(res.data)
            this.$message(res.data.msg)
            this.$message.success('验证码发送成功，请注意查收');
          }else{
            this.$message.error(res.data.data.errMsg)
          }

          console.log(res)
        })


      }


    },

    //获取cookie
    setCookie(name, pwd,exdays) {
      var exdate = new Date() // 获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays) // 保存的天数
      // 字符串拼接cookie
      window.document.cookie =
          'userName' + '=' + name + ';path=/;expires=' + exdate.toGMTString()
      window.document.cookie =
          'userPwd' + '=' + pwd + ';path=/;expires=' + exdate.toGMTString()
    },

    //保存cookie
    getCookie() {
      if (document.cookie.length > 0) {
        var arr = document.cookie.split('; ') // 这里显示的格式需要切割一下自己可输出看下
        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split('=') // 再次切割
          // 判断查找相对应的值
          if (arr2[0] === 'userName') {
            this.user.username = arr2[1]  // 保存到保存数据的地方即v-model
          } else if (arr2[0] === 'userPwd') {
            if(arr2[0] != null){
              this.loginAuto = true
            }
            this.user.password = arr2[1]
          }
        }
      }
    },

    toRegister(){
      this.$router.replace({path: '/register'})
    }
  }
}
</script>

<style scoped>
.login_title{
  text-align: center;
  font-size: 21px;
  color: #666;
  padding-left: 74px;
}
.login_title span{
  margin: 0 20px 0 20px;
  cursor: pointer;
}
.isActiveTitle{
  color: #333;
  font-weight: bolder;
}
</style>